﻿using Scap.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Scap.Info;
using System.Data;
using PagedList;
using Scap.Web.Models;
using Scap.Web.CommonCode;

namespace Scap.Web.Controllers
{
    public class tabsAreaController : Controller
    {
        private ScapData db = new ScapData();

        int _pageIndex = 0;
        public int PageIndex
        {
            get { return _pageIndex; }
            set { _pageIndex = value; }
        }

        int _pageSize = 15;
        //int _pageSize = 3;
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }

        //
        // GET: /tabsDepartamento/DeleteDepartamento
        public ActionResult DeleteDepartamento(int id = 0)
        {
            ScapDepartment scapdepartment = db.Departments.Find(id);
            if (scapdepartment == null)
            {
                return HttpNotFound();
            }
            else
            {
                db.Departments.Remove(scapdepartment);
                db.SaveChanges();
            }
            return RedirectToAction("Index", "Employee");
        }

        //
        // GET: /tabsDepartamento/AddDepartamento
        [NoCache]
        public PartialViewResult AddDepartamento(int? id)
        {
            int nId = Convert.ToInt32(id);
            int nTypeDepto = 0;

            IQueryable<ScapDepartment> qryDpto = null;
            IQueryable<ScapDepartmentType> qryTpDp = null;
            ScapDepartment departamento = null;
            ScapDepartmentType departamentotipo = null;

            //Obtiene los Departamentos
            qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Area");
            departamentotipo = qryTpDp.FirstOrDefault<ScapDepartmentType>();
            if (departamentotipo != null)
            {
                nTypeDepto = departamentotipo.Id;
            }

            if (nId == 0)
            {
                departamento = new ScapDepartment();
                departamento.TypeId = nTypeDepto;
            }
            else
            {
                departamento = db.Departments.Find(nId);
            }


            ViewBag.TypeId = new SelectList(db.DepartmentTypes, "Id", "Name");
            ViewBag.AddressId = new SelectList(db.LocationAddresses, "Id", "Name");
            ViewBag.ParentDepartmentId = new SelectList(db.Departments.Where(dpt => dpt.TypeId == nTypeDepto), "Id", "Name");
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
            ViewBag.deptoAreaIdHlp = "Area";

            return PartialView(departamento);
        }

        // 
        [HttpPost]
        [NoCache]
        public ActionResult AddDepartamento(ScapDepartment departamento)
        {
            int nTypeDepto = 0;
            string szMsg = "";

            nTypeDepto = departamento.TypeId;

            if (ModelState.IsValid)
            {
                db.Departments.Add(departamento);
                db.SaveChanges();
                return RedirectToAction("Index", "Employee");
            }
            else
            {
                //Mostar el error 
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        foreach (var itemError in item.Errors)
                        {
                            szMsg = string.Format("{0} {1}", szMsg, itemError.ErrorMessage);
                        }
                    }
                }
                TempData["MessageError"] = string.Format("No se pudo actualizar Departamento/Area: {0}", szMsg);
            }

            ViewBag.TypeId = new SelectList(db.DepartmentTypes, "Id", "Name");
            ViewBag.AddressId = new SelectList(db.LocationAddresses, "Id", "Name");
            ViewBag.ParentDepartmentId = new SelectList(db.Departments.Where(dpt => dpt.TypeId == nTypeDepto), "Id", "Name");
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
            ViewBag.deptoAreaIdHlp = "Area";

            return RedirectToAction("Index", "Employee");
        }

        //
        // GET: /tabsDepartamento/EditDepartamento
        [NoCache]
        public PartialViewResult EditDepartamento(int? id)
        {
            int nId = Convert.ToInt32(id);
            int nTypeDepto = 0;
            int nPos = 0;

            IQueryable<ScapDepartment> qryDpto = null;
            IQueryable<ScapDepartmentType> qryTpDp = null;
            IQueryable<ScapCompany> qryCia = null;
            ScapDepartment departamento = null;
            ScapDepartmentType departamentotipo = null;

            List<KeyValuePair<string, string>> optionList = null;
            SelectList selectHlp = null;


            //Obtiene los Departamentos
            qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Area");
            departamentotipo = qryTpDp.FirstOrDefault<ScapDepartmentType>();
            if (departamentotipo != null)
            {
                nTypeDepto = departamentotipo.Id;
            }

            if (nId == 0)
            {
                departamento = new ScapDepartment();
                departamento.TypeId = nTypeDepto;
            }
            else
            {
                departamento = db.Departments.Find(nId);
            }


            ViewBag.TypeId = new SelectList(db.DepartmentTypes, "Id", "Name");
            //ViewBag.AddressId = new SelectList(db.LocationAddresses, "Id", "Name");
            ViewBag.ParentDepartmentId = new SelectList(db.Departments.Where(dpt => dpt.TypeId == nTypeDepto), "Id", "Name");
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
            ViewBag.deptoAreaIdHlp = "Area";

            IQueryable<ScapLocationAddress> qryAdrs = db.LocationAddresses.OrderBy(cdi => cdi.Id);
            optionList = new List<KeyValuePair<string, string>>();
            if (qryAdrs.Count() > 0)
            {
                foreach (var itemCdi in qryAdrs)
                {
                    optionList.Add(new KeyValuePair<string, string>(itemCdi.Id.ToString(), itemCdi.Name));
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.AddressId = selectHlp;

            qryDpto = db.Departments.Where(dpt => dpt.TypeId == nTypeDepto).OrderBy(dpt => dpt.Id);
            optionList = new List<KeyValuePair<string, string>>();
            if (qryDpto.Count() > 0)
            {
                foreach (var itemCdi in qryDpto)
                {
                    optionList.Add(new KeyValuePair<string, string>(itemCdi.Name, itemCdi.Description));
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.ParentDepartmentId = selectHlp;

            qryCia = db.Companies.OrderBy(cis => cis.Id);
            optionList = new List<KeyValuePair<string, string>>();
            if (qryCia.Count() > 0)
            {
                foreach (var itemCdi in qryCia)
                {
                    optionList.Add(new KeyValuePair<string, string>(itemCdi.Id.ToString(), itemCdi.Description));
                }
            }
            selectHlp = new SelectList(optionList, "Key", "Value");
            ViewBag.CompanyId = selectHlp;

            return PartialView(departamento);
        }

        // 
        [HttpPost]
        [NoCache]
        public ActionResult EditDepartamento(ScapDepartment departamento, string ParentDepartmentHlpId)
        {
            int nTypeDepto = 0;
            int nParentId = 0;
            string szMsg = "";


            IQueryable<ScapDepartment> qryDpto = null;
            ScapDepartment padredepto = null;

            nTypeDepto = departamento.TypeId;

            if (ModelState.IsValid)
            {
                //Obtiene el id del padre
                qryDpto = db.Departments.Where(dpt => dpt.Name == ParentDepartmentHlpId);
                padredepto = qryDpto.FirstOrDefault<ScapDepartment>();
                if (padredepto != null)
                {
                    nParentId = padredepto.Id;
                    departamento.ParentDepartmentId = nParentId;
                }

                db.Entry(departamento).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index", "Employee");
            }
            else
            {
                //Mostar el error 
                foreach (var item in ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        foreach (var itemError in item.Errors)
                        {
                            szMsg = string.Format("{0} {1}", szMsg, itemError.ErrorMessage);
                        }
                    }
                }
                TempData["MessageError"] = string.Format("No se pudo actualizar Departamento/Area: {0}", szMsg);
            }

            ViewBag.TypeId = new SelectList(db.DepartmentTypes, "Id", "Name");
            ViewBag.AddressId = new SelectList(db.LocationAddresses, "Id", "Name");
            ViewBag.ParentDepartmentId = new SelectList(db.Departments.Where(dpt => dpt.TypeId == nTypeDepto), "Id", "Name");
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
            ViewBag.deptoAreaIdHlp = "Area";

            return RedirectToAction("Index", "Employee");
        }

        //
        // GET: /tabsArea/
        [NoCache]
        public PartialViewResult Index(int? page, string identificacionid)
        {
            bool bHasPreviousPage = false;
            bool bHasNextPage = false;
            int nTypeDepto = 0;
            int nHas = 0;
            int nPageCount = 1;
            int nPageNumber = 0;
            int pageIndex = 0;
            int pageSize = PageSize;

            IQueryable<ScapDepartment> qryDpto = null;
            IQueryable<ScapDepartmentType> qryTpDp = null;
            ScapDepartment departamento = null;
            ScapDepartmentType departamentotipo = null;

            //Obtiene los Departamentos
            qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Area");
            departamentotipo = qryTpDp.FirstOrDefault<ScapDepartmentType>();
            if (departamentotipo != null)
            {
                nTypeDepto = departamentotipo.Id;
            }

            List<ScapDepartment> deptoList = new List<ScapDepartment>();
            qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTypeDepto).OrderBy(dpto => dpto.Name);
            if (qryDpto.Count() > 0)
            {
                foreach (var item in qryDpto)
                {
                    deptoList.Add(item);
                }
            }

            //Set the page
            if (page == null)
            {
                pageIndex = 1;
            }
            else
            {
                pageIndex = Convert.ToInt32(page);
            }

            nHas = deptoList.Count;
            nPageCount = nHas / pageSize;

            var objList = deptoList.ToPagedList(pageIndex, pageSize);
            deptoList = new List<ScapDepartment>();
            foreach (var item in objList)
            {
                deptoList.Add(item);
            }

            //double nMod = nHas & pageSize;
            int nModi = nHas % pageSize;
            if (nModi == 0)
            {
                nPageCount = 1;
                bHasNextPage = false;
                bHasPreviousPage = false;
            }
            if (nModi < pageSize)
            {
                bHasNextPage = true;
                bHasPreviousPage = true;
                nPageCount++;

                if (pageIndex == 1)
                {
                    bHasPreviousPage = false;
                }
                if (nPageCount == pageIndex)
                {
                    bHasNextPage = false;
                }
            }

            nPageNumber = pageIndex;
            ViewBag.PageCount = nPageCount;
            ViewBag.PageNumber = nPageNumber;
            ViewBag.HasPreviousPage = bHasPreviousPage;
            ViewBag.HasNextPage = bHasNextPage;

            //Set the id of the main div
            ViewBag.MainDiv = "tabsAreadivId";

            //return PartialView(employeeList.ToPagedList(pageIndex, pageSize));
            return PartialView(deptoList);
        }

        //
        // GET: /tabsDepartamento/
        [NoCache]
        [HttpPost]
        public PartialViewResult Index(int? page, string nombredeptoid, string descripciondeptoid)
        {
            bool bHasPreviousPage = false;
            bool bHasNextPage = false;
            int nTypeDepto = 0;
            int nHas = 0;
            int nPageCount = 1;
            int nPageNumber = 0;
            int pageIndex = 0;
            int pageSize = PageSize;
            //pageSize = 2;

            IQueryable<ScapDepartment> qryDpto = null;
            IQueryable<ScapDepartmentType> qryTpDp = null;
            ScapDepartment departamento = null;
            ScapDepartmentType departamentotipo = null;

            //Obtiene los Departamentos
            qryTpDp = db.DepartmentTypes.Where(tpdp => tpdp.Name == "Area");
            departamentotipo = qryTpDp.FirstOrDefault<ScapDepartmentType>();
            if (departamentotipo != null)
            {
                nTypeDepto = departamentotipo.Id;
            }

            List<ScapDepartment> deptoList = new List<ScapDepartment>();
            qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTypeDepto).OrderBy(dpto => dpto.Name);

            if (!string.IsNullOrEmpty(nombredeptoid))
            {
                qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTypeDepto && dpto.Name.StartsWith(nombredeptoid)).OrderBy(dpto => dpto.Name);

            }


            if (!string.IsNullOrEmpty(descripciondeptoid))
            {
                qryDpto = db.Departments.Where(dpto => dpto.TypeId == nTypeDepto && dpto.Description.StartsWith(descripciondeptoid)).OrderBy(dpto => dpto.Name);

            }

            if (qryDpto.Count() > 0)
            {
                foreach (var item in qryDpto)
                {
                    deptoList.Add(item);
                }
            }

            //Set the page
            if (page == null)
            {
                pageIndex = 1;
            }
            else
            {
                pageIndex = Convert.ToInt32(page);
            }

            nHas = deptoList.Count;
            nPageCount = nHas / pageSize;

            var objList = deptoList.ToPagedList(pageIndex, pageSize);
            deptoList = new List<ScapDepartment>();
            foreach (var item in objList)
            {
                deptoList.Add(item);
            }


            //double nMod = nHas & pageSize;
            int nModi = nHas % pageSize;
            if (nModi == 0)
            {
                nPageCount = 1;
                bHasNextPage = false;
                bHasPreviousPage = false;
            }
            if (nModi < pageSize)
            {
                bHasNextPage = true;
                bHasPreviousPage = true;
                nPageCount++;

                if (pageIndex == 1)
                {
                    bHasPreviousPage = false;
                }
                if (nPageCount == pageIndex)
                {
                    bHasNextPage = false;
                }
            }

            nPageNumber = pageIndex;
            ViewBag.PageCount = nPageCount;
            ViewBag.PageNumber = nPageNumber;
            ViewBag.HasPreviousPage = bHasPreviousPage;
            ViewBag.HasNextPage = bHasNextPage;

            //Set the id of the main div
            ViewBag.MainDiv = "tabsAreadivId01";


            return PartialView(deptoList);
        }

    }
}
